<template>
    <Page>
        <el-form ref="form" :model="form" >
            <Panel title="店铺信息">
                <el-form ref="myForm" :model="form" :rules="formRules">
                    <el-form-item label="父类分级" prop="pid_level">
                        <el-tree
                            ref="menuTree"
                            :data="listData"
                            node-key="id"
                            :props="{
                                label: 'name',
                                children: 'children'
                            }"
                            highlight-current
                            :expand-on-click-node="false"
                            @node-click="handleNodeClick"
                            default-expand-all
                        >
                            <span class="custom-tree-node" slot-scope="{ node, data }">
                                <span>{{ node.label }}</span>
                                <span class="menu-info" v-if="data.controller_name">
                                    ({{ data.controller_name }}/{{ data.action_name }})
                                </span>
                            </span>
                        </el-tree>
                    </el-form-item>
                    <el-form-item label="标题" prop="name">
                        <el-input v-model="form.name" size="small"></el-input>
                    </el-form-item>
                    <el-form-item label="控制器名" prop="controller_name">
                        <el-input v-model="form.controller_name" size="small"></el-input>
                    </el-form-item>
                    <el-form-item label="方法名" prop="action_name">
                        <el-input  v-model="form.action_name" size="small"></el-input>
                    </el-form-item>
                    <el-form-item label="图标" prop="code">
                        <el-input  v-model="form.code" size="small"></el-input>
                    </el-form-item>
                    <el-form-item label="排序" prop="sort">
                        <el-input type="number" v-model="form.sort" size="small"></el-input>
                    </el-form-item>
                    <el-form-item label="路由地址" prop="url">
                        <el-input  v-model="form.url" size="small"></el-input>
                    </el-form-item>
                    <el-form-item label="导航状态" prop="state">
                        <el-radio-group v-model="form.state">
                            <el-radio :label="1">显示</el-radio>
                            <el-radio :label="0">隐藏</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
            </Panel>
            <Panel title="">
                <el-form-item>
                    <el-button type="primary" size="small" @click="onSubmit('form')">提交</el-button>
                </el-form-item>
            </Panel>
        </el-form>
    </Page>
</template>

<script>
import Page from "@/components/page/Page";
import Panel from "@/components/panel/Panel";

export default {
    data() {
        return {
            form: {
                pid_level: '',    // 店铺地址
                name: '',      // 店铺电话
                controller_name: '',      // 营业时间
                action_name: '',      // 经营商品
                code: '',      // 经营商品
                url: '',      // 经营商品
                sort: '',      // 经营商品
                state: null,      // 初始值设置为 null，与 el-radio-group 类型匹配
                id:0
            },
            formRules: {
                pid_level: [
                    { required: true, message: '请选择父类分级', trigger: 'change' }
                ],
                name: [
                    { required: true, message: '请输入标题', trigger: 'blur' }
                ],
                controller_name: [
                    { required: true, message: '请输入控制器名', trigger: 'blur' }
                ],
                action_name: [
                    { required: true, message: '请输入方法名', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入图标', trigger: 'blur' }
                ],
                url: [
                    { required: true, message: '请输入路由地址', trigger: 'blur' }
                ],
                sort: [
                    { required: true, message: '请输入排序', trigger: 'blur' },
                ],
                state: [
                    { required: true, message: '请选择状态', trigger: 'change' }
                ]
            },
            mchTypeList: { 12: '企业', 11: '个体工商户' },
            agree: false,
            areaCode: [],
            areaList: [],
            showButtonText:{},
            listData:[],
            pidlevel:""
        }
    },
    created() {},
    mounted() {
        this.initData();
        // 其余字段直接赋值
        this.form.name = this.$route.query.data.name
        this.form.controller_name = this.$route.query.data.controller_name
        this.form.action_name = this.$route.query.data.action_name
        this.form.code = this.$route.query.data.code
        this.form.url = this.$route.query.data.url
        this.form.sort = this.$route.query.data.sort
        this.form.state = this.$route.query.data.state
        this.form.id = this.$route.query.data.id

    },
    methods: {
        handleNodeClick(data) {
            // 设置选中的父级ID
            this.form.pid_level = `${data.id}_${data.level || 1}`;
        },
        initData() {
            this.$http.get('/admin/AuthNode/listsNew', {params: this.params }).then(result => {
                if (result.code === 200) {
                    // 处理数据，确保每个节点都有正确的层级信息
                    const processNode = (node, level = 0) => {
                        node.level = level;
                        if (node.children && node.children.length) {
                            node.children.forEach(child => processNode(child, level + 1));
                        }
                        return node;
                    };

                    this.listData = Array.isArray(result.data) ? result.data : Object.values(result.data);
                    this.listData.forEach(node => processNode(node));

                    // 如果有编辑数据，找到并选中对应节点
                    this.$nextTick(() => {
                        if (this.$route.query.data && this.$route.query.data.pid) {
                            const pid = Number(this.$route.query.data.pid);
                            const node = this.findNodeById(this.listData, pid);
                            if (node) {
                                this.$refs.menuTree.setCurrentKey(pid);
                                this.form.pid_level = `${pid}_${node.level || 1}`;
                            }
                        }
                    });
                } else {
                    this.$message.error(result.msg);
                }
            });
        },
        // 递归查找id链路
        findPathById(tree, id, path = []) {
            for (let node of tree) {
                const newPath = path.concat(node.id);
                if (node.id === id) {
                    return newPath;
                }
                if (node.children && node.children.length) {
                    const res = this.findPathById(node.children, id, newPath);
                    if (res.length) return res;
                }
            }
            return [];
        },
        // 递归查找节点
        findNodeById(tree, id) {
            for (let node of tree) {
                if (node.id === id) return node;
                if (node.children && node.children.length) {
                    const res = this.findNodeById(node.children, id);
                    if (res) return res;
                }
            }
            return null;
        },
        // 提交数据
        onSubmit(form) {
            this.$refs['myForm'].validate((valid) => {
                if (valid) {
                    // 处理父级分类数据
                    if (Array.isArray(this.form.pid_level) && this.form.pid_level.length > 0) {
                        const lastId = this.form.pid_level[this.form.pid_level.length - 1];
                        const node = this.findNodeById(this.listData, lastId);
                        if (node) {
                            this.form.pid_level = `${node.id}_${node.level}`;
                        } else {
                            this.form.pid_level = '';
                        }
                    } else if (this.form.pid_level === null || this.form.pid_level === '') {
                        this.form.pid_level = '';
                    }

                    this.$http.post('/admin/AuthNode/edit', this.form).then(result => {
                        if (result.code == 200) {
                            this.$message.success(result.msg);
                            this.$router.back();
                        } else {
                            this.$message.error(result.msg);
                        }
                    });
                }
            });
        },
    },
    components: {
        Page,
        Panel
    }
}
</script>

<style lang="less" scoped>
::v-deep(.el-upload){
    .el-upload-dragger{
        height:120px;
        width:180px;
    }
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;

    .menu-info {
        font-size: 12px;
        color: #909399;
    }
}

::v-deep(.el-tree) {
    background: none;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    padding: 10px;
    max-height: 400px;
    overflow-y: auto;

    .el-tree-node__content {
        height: 32px;

        &:hover {
            background-color: #F5F7FA;
        }
    }

    .el-tree-node.is-current > .el-tree-node__content {
        background-color: #ecf5ff;
        color: #409EFF;
    }
}
</style>
